package com.gthncz;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.gthncz.bean.User;
import com.gthncz.mapper.UserMapper;

@SpringBootApplication
public class MyBatisDemoApplication implements CommandLineRunner {
	
	/**
	 * 实现了两种方式的 MyBatis 使用 
	 * 1. 使用接口方式的 Mapper, ``sqlSession.getMapper()``
	 * 2. 使用 namespace+id 方式的 Mapper, ``sqlSession.insert, select 等等``
	 */
	
	public void test() throws IOException {
		Reader reader = Resources.getResourceAsReader("config/mybatis-config.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		// 开始业务逻辑
		UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
		User user = userMapper.findById(1L); // Long 类型要加 `L`
		System.out.println(user.toString());
		
		sqlSession.close();
	}
	
	public void test2() throws IOException {
		Reader reader = Resources.getResourceAsReader("config/mybatis-config.xml");
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
		SqlSession sqlSession = sqlSessionFactory.openSession();
		
		// 开始业务逻辑
		List<User> users = sqlSession.selectList("com.gthncz.mapper.UserListMapper.listAllUsers");
		System.out.println("--------------------------------------------");
		for(User user: users) {
			System.out.println(user.toString());
		}
		System.out.println("--------------------------------------------");
		sqlSession.close();
	}

	public static void main(String[] args) {
		SpringApplication.run(MyBatisDemoApplication.class, args);
	}

	@Override
	public void run(String... args) throws Exception {
		test();
		test2();
	}

}
